package com.wondream.myframework.app.mybatis.plugin;

import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.AbstractJavaMapperMethodGenerator;

import java.util.TreeSet;

/**
 * 添加findByCondition方法
 */
public class CustomJavaMapperMethodGenerator extends AbstractJavaMapperMethodGenerator {
    @Override
    public void addInterfaceElements(Interface anInterface) {
        addInterfaceList(anInterface);
    }

    private void addInterfaceList(Interface interfaze) {
        // 1.先创建import对象
        TreeSet<FullyQualifiedJavaType> importedTypes = new TreeSet<>();
        // 2.添加list的包
        importedTypes.add(FullyQualifiedJavaType.getNewListInstance());
        // 3.创建方法对象
        Method method = new Method();
        // 4.设置该方法为public
        method.setVisibility(JavaVisibility.PUBLIC);
        // 5.设置返回类型是List
        FullyQualifiedJavaType returnType = FullyQualifiedJavaType.getNewListInstance();
        FullyQualifiedJavaType listType;
        // 6.设置List的类型是实体类的对象
        listType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        importedTypes.add(listType);
        // 7.返回类型对象设置为List
        returnType.addTypeArgument(listType);
        // 8.方法对象设置返回类型对象
        method.setReturnType(returnType);
        // 9.设置方法名称
        method.setName("findByCondition");
        // 10.设置参数类型是对象
        FullyQualifiedJavaType parameterType;
        parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        // 11.import参数类型是对象
        importedTypes.add(parameterType);
        // 12.为方法添加参数，变量名称record
        method.addParameter(new Parameter(parameterType, "record"));
        // 13.more
        addMapperAnnotations(interfaze, method);
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
        if(context.getPlugins().clientSelectByPrimaryKeyMethodGenerated(method, interfaze, introspectedTable)){
            interfaze.addImportedTypes(importedTypes);
            interfaze.addMethod(method);
        }

    }

    private void addMapperAnnotations(Interface interfaze, Method method) {
    }
}
